package procsim;

public class Counter extends Register{
    private Signal incS, decS;
    public Counter(int numOfBits, int init, MSignal in){
        super(numOfBits, init, in);
        name="CNT";
    }
    public Counter(int numOfBits, int init, MSignal in, String name){
        super(numOfBits, init, in, name);
    }
    public Counter inc(){ // inkrementiranje po odgovarajucem modulu
        val=(val+1)%(int)Math.pow(2, bits);
        return this;
    }
    public Counter dec(){ // dekrementiranje po odgovarajucem modulu
        val=(val-1)%(int)Math.pow(2, bits);
        return this;
    }
    public Counter setIncSignal(Signal inc){
        if(inc!=null) inc.addElement(this);
        incS=inc;
        if(decS!=null) decS.set(0);
        deactivateLoadClear();
        return this;
    }
    public Counter setDecSignal(Signal dec){
        if(dec!=null) dec.addElement(this);
        decS=dec;
        if(incS!=null) incS.set(0);
        deactivateLoadClear();
        return this;
    }
    public Counter ammendInc(Signal sig){
        incS.set(sig.get());
        return this;
    }
    @Override
    public Counter tick() {
        if(incS!= null && !incS.isNull())
            inc();
        if(decS!= null && !decS.isNull())
            dec();
        super.tick();
        return this;
    }
    @Override
    public void updateSignal(Sig sig){
        super.updateSignal(sig);
        if(incS!=null && incS==sig)
            incS.set(sig.get(), false);
        if(decS!=null && decS==sig)
            decS.set(sig.get(), false);
    }
}
